package com.bobo.controller;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bobo.base.R;
import com.bobo.base.token.SysTypeEnum;

import com.bobo.pojo.User;
import com.bobo.pojo.bo.UserInfoInTokenBO;
import com.bobo.pojo.vo.TokenInfoVO;
import com.bobo.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.Map;

/**
 * 用户信息
 *
 * @author SJL
 */
@RestController
@Tag(name = "微信一键登录相关接口")
public class WechatLoginController {
    private static final Logger logger = LoggerFactory.getLogger(WechatLoginController.class);

    @Resource
    private UserService userService;


    // 从配置文件中获取微信小程序的 appid 和 secret
    @Value("${wechat.appid}")
    private String appid;
    @Value("${wechat.secret}")
    private String secret;

    /**
     * 微信一键登录接口
     * @param request 包含 code、nickName、avatarUrl 的请求体
     * @return 包含 token 信息的响应实体
     */
    @PostMapping("/wechat/login")
    @Operation(summary = "微信一键登录", description = "使用微信 code 进行登录或注册")
    public R<TokenInfoVO> wechatLogin(@RequestBody Map<String, String> request) {
        String code = request.get("code");
        String nickName = request.get("nickName");
        String avatarUrl = request.get("avatarUrl");

        if (code == null) {
            R.failure("缺少 code 参数");
        }

        // 调用微信接口换取 openid
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<String> entity = new HttpEntity<>(headers);
        try {
            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
            String result = response.getBody();
            JSONObject jsonObject = JSONObject.parseObject(result);
            String openid = jsonObject.getString("openid");

            if (openid == null) {
                R.failure("获取 openid 失败");
            }

            // 根据 openid 查询用户是否存在
            User user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getOpenid, openid));
            if (user == null) {
                // 用户不存在，进行注册
                user = new User();
                user.setOpenid(openid);
                user.setNickName(nickName);
                user.setAvatarUrl(avatarUrl);
                user.setUserId(IdUtil.simpleUUID());
                user.setStatus(1);
                user.setUserRegtime(new Date());
                user.setModifyTime(new Date());
                userService.save(user);
            } else {
                // 用户存在，更新昵称和头像
                user.setNickName(nickName);
                user.setAvatarUrl(avatarUrl);
                userService.updateById(user);
            }

            // 生成 token
            UserInfoInTokenBO userInfoInTokenBO = new UserInfoInTokenBO();
            userInfoInTokenBO.setUserId(user.getUserId());
            userInfoInTokenBO.setSysType(SysTypeEnum.ORDINARY.value());
            userInfoInTokenBO.setIsAdmin(0);
            userInfoInTokenBO.setEnabled(true);

            // 替换token生成逻辑 ↓
            TokenInfoVO tokenInfoVO = new TokenInfoVO();
            tokenInfoVO.setAccessToken(IdUtil.simpleUUID());  // 使用UUID生成token
            tokenInfoVO.setRefreshToken(IdUtil.simpleUUID());
            tokenInfoVO.setExpiresIn(7200);                   // 设置2小时有效期
            return R.success(tokenInfoVO);
        } catch (Exception e) {
         return  R.success("调用微信接口失败: " + e.getMessage());
        }
    }
}
